package com.x.chat.service;

import com.alibaba.fastjson.JSONObject;
import com.x.chat.pojo.ChatItem;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/websocket/{uid}")
public class WebSocketService {
    private static Map<Long, Session> sessions = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("uid") long uid) {
        if (sessions.containsKey(uid)) {
            // 存在已有的用户
            try {
                sessions.get(uid).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sessions.put(uid, session);
    }

    @OnMessage
    public void onMessage(Session session, @PathParam("uid") String uid, String msg) {

    }

    @OnClose
    public void onClose(Session session, @PathParam("uid") long uid) {
        sessions.remove(uid);
    }

    @OnError
    public void onError(Session session, @PathParam("uid") long uid, Throwable throwable) {
        sessions.remove(uid);
        throwable.printStackTrace();
    }

    public static Map<Long, Session> getMap() {
        return sessions;
    }

    public boolean sencMessageToUser(long userId, ChatItem rcvChatItem) {
        Session session = sessions.get(userId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(JSONObject.toJSONString(rcvChatItem));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }
}
